<template>
  <el-dropdown>
    <span class="el-dropdown-link">
      工具箱
      <el-icon class="el-icon--right">
        <arrow-down />
      </el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="beginMeasureLength">测量长度</el-dropdown-item>
        <el-dropdown-item @click="beginMeasureArea">测量面积</el-dropdown-item>
        <el-dropdown-item @click="clearDraw">停止测量</el-dropdown-item>
        <el-dropdown-item @click="downloadMap">导出图片</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { ArrowDown } from '@element-plus/icons-vue';
import { measureLength } from './Hooks/usemeasureLength';
import { measureArea } from './Hooks/usemeasureArea';
import FileSaver from 'file-saver';

const $map = ref(null);
//存储返回的画笔,用于判断有无画笔和移除画笔
const nowDraw = ref(null);

onMounted(() => {
  $map.value = inject('$map');
});

const beginMeasureLength = () => {
  //如何有画笔,先移除画笔
  if (nowDraw.value) {
    $map.value.removeInteraction(nowDraw.value);
  }
  const { draw } = measureLength($map.value);
  nowDraw.value = draw;
};

const beginMeasureArea = () => {
  if (nowDraw.value) {
    $map.value.removeInteraction(nowDraw.value);
  }
  const { draw } = measureArea($map.value);
  nowDraw.value = draw;
};

const clearDraw = () => {
  if (nowDraw.value) {
    //移除画笔
    $map.value.removeInteraction(nowDraw.value);
    //筛选出需要删除的图层
    const removeLayers = $map.value.getLayers().array_.filter((item) => {
      if (
        item.values_.title === '长度标注' ||
        item.values_.title === '面积标注' ||
        item.values_.title === '长度画笔' ||
        item.values_.title === '面积画笔'
      ) {
        return true;
      }
    });
    removeLayers.forEach((item) => {
      $map.value.removeLayer(item);
    });
  }
};

const downloadMap = () => {
  $map.value.once('postcompose', function (event) {
    const canvas = event.context.canvas;
    canvas.toBlob(function (blob) {
      FileSaver.saveAs(blob, 'map.png');
    });
  });
  $map.value.renderSync();
};
</script>

<style lang="scss" scoped>
.el-dropdown {
  height: 100%;
  display: flex;
  align-items: center;
  color: #131313;
  font-size: 17px;

  :deep(:focus-visible) {
    outline: none !important;
  }
}
</style>
